package com.chery.media.service

import android.annotation.SuppressLint
import android.app.DownloadManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Environment
import android.os.IBinder
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.Utils
import java.io.File

class DownloadService: Service() {

    private var downloadManager: DownloadManager? = null

    private var downloadId: Long = 0L

    private var isQuery = true

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val downloadUrl = intent?.getStringExtra("downloadUrl")
        downloadApk(downloadUrl?:"")
        return START_NOT_STICKY
    }

    /**
     * 下载apk
     */
    private fun downloadApk(downloadUrl: String) {
        val request = DownloadManager.Request(Uri.parse(downloadUrl))
        request.setTitle("file download")
        request.setDescription("downloading file…")
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "chery_media.apk")
        downloadManager = Utils.getApp().getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
        downloadId = downloadManager?.enqueue(request)?:0L
        queryDownloadStatus()
    }

    private fun queryDownloadStatus() {
        Thread {
            while (isQuery) {
                downloadStatus()
                try {
                    Thread.sleep(500)
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
            }
        }.start()
    }

    @SuppressLint("Range")
    private fun downloadStatus() {
        val query = DownloadManager.Query()
        query.setFilterById(downloadId)
        val cursor = downloadManager?.query(query)
        if (cursor?.moveToFirst() == true) {
            val status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))
            when (status) {
                DownloadManager.STATUS_PAUSED -> {
                    LogUtils.eTag("DownloadManager", "下载暂停")
                }
                DownloadManager.STATUS_PENDING -> {
                    LogUtils.eTag("DownloadManager", "下载延迟")
                }
                DownloadManager.STATUS_RUNNING -> {
                    LogUtils.eTag("DownloadManager", "正在下载")
                }
                DownloadManager.STATUS_SUCCESSFUL -> {
                    LogUtils.eTag("DownloadManager", "下载完成")
                    isQuery = false
                    AppUtils.installApp(File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "chery_media.apk"))
                    stopSelf()
                }
                DownloadManager.STATUS_FAILED -> {
                    LogUtils.eTag("DownloadManager", "下载失败")
                    isQuery = false
                    stopSelf()
                }
            }
        }
    }

}